package com.speak.sparkadminserver.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.speak.sparkadminserver.domain.NutUser;
import com.speak.sparkadminserver.service.NutRolePowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/2/20 16:48
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private NutRolePowerService service;
    @Autowired
    private static final ObjectMapper mapper= new ObjectMapper();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }
        String json = null;
        NutUser user = null;
        try {
            json = template.opsForValue().get("token:" + token);
        }catch (Exception e){
            System.out.println("用户未登录");
            return;
        }
        try{
            user = mapper.readValue(json, NutUser.class);
        }catch (Exception e){
            System.out.println("token非法");
            return;
        }
        //TODO:这里的权限验证有点问题，但是已经不好修改了。应该是再创建一个表用于存储用户身份数据
        List<GrantedAuthority> auths = new ArrayList<>();
        List<Integer> integers = service.AuthList(user.getId());
        Iterator<Integer> iterator = integers.iterator();
        while(iterator.hasNext()){
            auths.add(new SimpleGrantedAuthority(String.valueOf(iterator.next())));
        }
        User user1 = new User(user.getUsername(),user.getPassword(),auths);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user1,null,user1.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
